package com.fagertveit.chainsawrus.graphics;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;

import android.opengl.GLES20;

public class Sprite {
	private float texX;
	private float texY;
	private float texWidth;
	private float texHeight;
	private float u[] = new float[2];
	private float v[] = new float[2];
	
	private short indices[] = {
			0, 1, 2, 2, 1, 3
		};
	
	public Sprite(float texX, float texY, float texWidth, float texHeight) {
		this.texX = texX;
		this.texY = texY;
		this.texWidth = texWidth;
		this.texHeight = texHeight;
	}
	
	public void genUV(float srcWidth, float srcHeight) {
		u[0] = texX / srcWidth;
		u[1] = (texX + texWidth) / srcWidth;
		v[0] = texY / srcHeight;
		v[1] = (texY + texHeight) / srcHeight;
	}
	
	public float[] getVertices(float x, float y) {
		float vertices[] = {
			x, y,                //Top Left V
			u[0], v[0],          //Top Left uv
			x, y + texHeight,    //Bottom Left V
			u[0], v[1],          //Bottom Left uv
			x + texWidth, y,     //Top Right V
			u[1], v[0],          //Top Right uv
			x + texWidth, y + texHeight, //Bottom Right V
			u[1], v[1]           //Bottom Right uv
		};
		return vertices;
	}
	
	public void render(float x, float y) {
		float vertices[] = getVertices(x, y);
		
		FloatBuffer vertexBuffer = ByteBuffer.allocateDirect(vertices.length * 4)
        .order(ByteOrder.nativeOrder()).asFloatBuffer();
		vertexBuffer.put(vertices).position(0);
		
		ShortBuffer indexBuffer = ByteBuffer.allocateDirect(indices.length * 2)
        .order(ByteOrder.nativeOrder()).asShortBuffer();
		indexBuffer.put(indices).position(0);
		
		vertexBuffer.position(0);
	    GLES20.glVertexAttribPointer(0, 2, GLES20.GL_FLOAT, false, 16, vertexBuffer);
        
	    vertexBuffer.position(2);
        GLES20.glVertexAttribPointer(1, 2, GLES20.GL_FLOAT, false, 16, vertexBuffer);
        
        GLES20.glEnableVertexAttribArray(1);
        GLES20.glEnableVertexAttribArray(0);

        GLES20.glDrawElements(GLES20.GL_TRIANGLES, 6, GLES20.GL_UNSIGNED_SHORT, indexBuffer);
	}
}
